package org.example;

import com.alibaba.excel.EasyExcel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.example.DTO.MatchInfoDTO;
import org.example.listener.MatchListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * Hello world!
 */
public class App {

    //绝对路径
    private static String parentPath = System.getProperty("user.dir");
    //结果输出的路径
    private static String resultPath = parentPath + "\\ywm_result";
    //需要处理的pdf文件夹所在路径
    private static String pdfListPath = parentPath + "\\pdfList";
    //信息匹配excel路径
    private static String matchInfoPath = parentPath + "\\matchInfo\\matchInfo.xlsx";
    //是否添加人名为后缀
    private static String addUserNameStatus = "N";
    //报表名
    private static final String REPORT_NAME = "-销售报表";
    //计算表
    private static final String CALCULATION_TABLE_NAME = "-提成租金计算表";
    //自定义后缀
    private static String customSuffixesStatus = "N";
    //自定义后缀名
    private static String customSuffixesName = "";

    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream(parentPath + "/config/config.properties");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        properties.load(bufferedInputStream);
        addUserNameStatus = properties.getProperty("product.code.status");
        customSuffixesStatus = properties.getProperty("custom.suffixes.status");
        customSuffixesName = properties.getProperty("custom.suffixes.name");
        System.out.println("您的配置信息如下------");
        System.out.println("是否通过店名匹配负责人:" + addUserNameStatus);
        System.out.println("是否添加后缀:" + customSuffixesStatus);
        if ("Y".equalsIgnoreCase(customSuffixesStatus)) {
            System.out.println("需要添加的自定义后缀名:" + customSuffixesName);
        }
        File fileDirectory = new File(resultPath);
        if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
            fileDirectory.mkdir();
        }
        List<MatchInfoDTO> matchInfoList = new ArrayList<>();
        if ("Y".equalsIgnoreCase(addUserNameStatus)) {
            //需要通过店名匹配名字，在文件名后缀添加负责人姓名
            matchInfoList = getMatchInfoList();
        }

        try {
            File folder = new File(pdfListPath);
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().endsWith(".pdf")) {
                        try {
                            processPDF(file, matchInfoList);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
//            System.out.println("开始重命名>>>>>>");
//            for (File file : files) {
//                if (file.getName().toLowerCase().endsWith(".pdf")) {
//                    PDDocument document = PDDocument.load(file);
//                    PDFTextStripper textStripper = new PDFTextStripper();
//                    String text = textStripper.getText(document);
//                    String[] lines = text.split("\\r?\\n");
//                    String firstLine = "";
//                    for (String line : lines) {
//                        if (line.contains(REPORT_NAME) || line.contains(CALCULATION_TABLE_NAME)) {
//                            firstLine = line.trim();
//                            break;
//                        }
//                    }
//                    firstLine = firstLine.replaceAll("\\s+", "");
//                    if ("Y".equalsIgnoreCase(addUserNameStatus) && !CollectionUtils.isEmpty(matchInfoList)) {
//                        String finalFirstLine = firstLine;
//                        List<MatchInfoDTO> matchResultList = matchInfoList.stream().filter(
//                                s -> finalFirstLine.contains(s.getStoreName().replaceAll("\\s+", ""))).collect(Collectors.toList());
//                        if (!CollectionUtils.isEmpty(matchResultList) && "Y".equals(customSuffixesStatus)) {
//                            firstLine += customSuffixesName + "(" + matchResultList.get(0).getUserName() + ")";
//                        }
//                        if (!CollectionUtils.isEmpty(matchResultList) && "N".equals(customSuffixesStatus)) {
//                            firstLine += "(" + matchResultList.get(0).getUserName() + ")";
//                        }
//                    }
//                    if ("N".equalsIgnoreCase(addUserNameStatus) && "Y".equals(customSuffixesStatus)) {
//                        firstLine += customSuffixesName;
//                    }
//                    String newName = resultPath + "\\" + firstLine + ".pdf";
//                    File newFile = new File(newName);
//                    document.close();
//                    FileUtils.copyFile(file, newFile);
//                    System.out.println("Renamed file: " + file.getName() + " ------> " + newFile.getName());
//                }
//            }
//            System.out.println("程序执行完毕！！！");
//            System.out.println("Press Enter to exit...");
//            Scanner scanner = new Scanner(System.in);
//            scanner.nextLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取匹配信息
     *
     * @return 响应
     */
    private static List<MatchInfoDTO> getMatchInfoList() {
        List<MatchInfoDTO> dataList = new ArrayList<>();
        EasyExcel.read(matchInfoPath, MatchInfoDTO.class, new MatchListener(dataList)).sheet().doRead();
        return dataList;
    }

    /**
     * 切割pdf
     *
     * @param pdfFile          pdf文件内容
     * @param matchInfoDTOList 匹配信息
     * @throws IOException 异常
     */
    public static void processPDF(File pdfFile, List<MatchInfoDTO> matchInfoDTOList) throws IOException {
        PDDocument document = PDDocument.load(pdfFile);
        String baseFileName = pdfFile.getName().substring(0, pdfFile.getName().lastIndexOf("."));
        String outputFolder = pdfFile.getParent() + File.separator + baseFileName;
        File outputDir = new File(outputFolder);
        if (!outputDir.exists()) {
            outputDir.mkdir();
        }
        int totalPages = document.getNumberOfPages();
        for (int i = 0; i < totalPages; i++) {
            PDDocument newDoc = new PDDocument();
            PDPage page = document.getPage(i);
            newDoc.addPage(page);
            PDFTextStripper textStripper = new PDFTextStripper();
            String newFileName = i + "-Page-" + (i + 1) + ".pdf";
            newDoc.save(outputFolder + File.separator + newFileName);
            newDoc.close();
        }
        document.close();
    }

    public static String extractTextFromPage(PDDocument document, int pageNumber) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setStartPage(pageNumber);
        stripper.setEndPage(pageNumber);
        return stripper.getText(document);
    }



}


